package com.hundsun.hsOffer.intercept;

import com.hundsun.hsOffer.model.SysLog;
import com.hundsun.hsOffer.utils.DateUtils;
import com.hundsun.hsOffer.utils.StringUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @author giegie
 * 日志拦截器
 */
public class SysLogInterceptor implements Interceptor {

    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        HttpServletRequest request = controller.getRequest();
        SysLog sysLog = new SysLog();
        sysLog.setCreateTime(DateUtils.formatDate(new Date()));
        sysLog.setMethod(inv.getMethodName());
        sysLog.setRemoteAddr(request.getRemoteAddr());
        String browser = request.getHeader("User-Agent");
        sysLog.setUserAgent(browser);
        String uri = request.getRequestURI();
        sysLog.setUri(uri);
        String host = request.getRemoteHost();
        sysLog.setHost(host);
        Map paramMap = request.getParameterMap();
        if (paramMap == null){
            return;
        }
        StringBuilder params = new StringBuilder();
        for (Map.Entry<String, String[]> param : ((Map<String, String[]>)paramMap).entrySet()){
            params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
            String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
            params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase(param.getKey(), "password") ? "" : paramValue, 100));
        }
        sysLog.setParams(params.toString());
        inv.invoke();
        sysLog.save();
    }



}
